package com.exm.collectcodenew.juc.aqs;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

//FutureTask也可以用作闭锁，它是通过Callabale来实现，相当于一种可以生成结果的Runnable，并且可以处于以下3种状态：等待状态，正在运行和运行完成。
// Future.get的行为取决于任务的状态，如果任务已经完成，那么get会立即返回结果，否则get将阻塞到任务进入完成状态，然后返回结果或者抛出异常。
public class FutureTaskAsShutting {
    class Cat {
        private String catName;

        public String getCatName() {
            return catName;
        }
        public void setCatName(String catName) {
            this.catName = catName;
        }

        @Override
        public String toString() {
            return "Cat{" +
                    "catName='" + catName + '\'' +
                    '}';
        }


    }
    private final FutureTask<Cat> future = new FutureTask<Cat>(new Callable<Cat>() {
        @Override
        public Cat call() throws InterruptedException {
            Cat cat = new Cat();
            cat.setCatName("罗⼩黑");
            for (int i = 1; i <= 5; i ++) {
// 睡眠1秒，⽅方便便⼤大家看执⾏行行效果
                Thread.sleep(1000L);
                System.out.println("Sleep " + i + " 秒");
            }
            return cat;
        }
    });
    private final Thread thread = new Thread(future);
    public void start() {
        System.out.println("启动Start");
        thread.start();
    }
    public Cat get() throws ExecutionException, InterruptedException {
        Cat cat = null;
        try {
            System.out.println("开始获取数据！");
            // 阻塞，等待线程执⾏行行完毕
            cat = future.get();
            System.out.println("获取数据成功！");
        } catch (ExecutionException e) {
            // 异常处理理，省略略...
        }
        return cat;
    }
    public static void main(String args[]) throws ExecutionException, InterruptedException {
        FutureTaskAsShutting preloader = new FutureTaskAsShutting();
        preloader.start();
        Cat cat = preloader.get();
        System.out.println(cat.toString());
    }
}
